package com.bsf.sonar;

/**
 * @author: chejiangyi
 * @create: 2019-05-10 09:45
 **/
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
//@WebFilter(urlPatterns = { "/api/v/*" }, filterName = "tokenAuthorFilter")
public class UrlFilter implements Filter {

    @Resource
    private Sonar sonar;

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;

        //设置允许跨域的配置
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        rep.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的访问方法
        rep.setHeader("Access-Control-Allow-Methods", "*");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        String projectName = request.getParameter("projectname");
        String result = sonar.run(projectName);
        response.getWriter().println(result);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}